<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * @category   Hamania
 * @package    Hamania_CashOnRelay
 * @copyright  Copyright (c) 2010 Hamania Medien GmbH & Co. KG (http://www.hamania-medien.de)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

class Hamania_CashOnRelay_Model_Invoice_Total extends Mage_Sales_Model_Order_Invoice_Total_Abstract
{
    public function collect(Mage_Sales_Model_Order_Invoice $invoice)
    {
        $order = $invoice->getOrder();

        if ($order->getPayment()->getMethodInstance()->getCode() != 'cashonrelay'){
            return $this;
        }

        if (!$order->getCorFee()){
            return $this;
        }

        foreach ($invoice->getOrder()->getInvoiceCollection() as $previusInvoice) {
            if ($previusInvoice->getCorAmount() && !$previusInvoice->isCanceled()) {
                $includeCorTax = false;
            }
        }

        $baseCorFee = $order->getBaseCorFee();
        $baseCorFeeInvoiced = $order->getBaseCorFeeInvoiced();
        $baseInvoiceTotal = $invoice->getBaseGrandTotal();
        $corFee = $order->getCorFee();
        $corFeeInvoiced = $order->getCorFeeInvoiced();
        $invoiceTotal = $invoice->getGrandTotal();

        if (!$baseCorFee || $baseCorFeeInvoiced==$baseCorFee) {
            return $this;
        }

        $baseCorFeeToInvoice = $baseCorFee - $baseCorFeeInvoiced;
        $corFeeToInvoice = $corFee - $corFeeInvoiced;

        $baseInvoiceTotal = $baseInvoiceTotal + $baseCorFeeToInvoice;
        $invoiceTotal = $invoiceTotal + $corFeeToInvoice;

        $invoice->setBaseGrandTotal($baseInvoiceTotal);
        $invoice->setGrandTotal($invoiceTotal);

        $invoice->setBaseCorFee($baseCorFeeToInvoice);
        $invoice->setCorFee($corFeeToInvoice);

        $order->setBaseCorFeeInvoiced($baseCorFeeInvoiced+$baseCorFeeToInvoice);
        $order->setCorFeeInvoiced($corFeeInvoiced+$corFeeToInvoice);

        return $this;
    }
}